﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Users.Sso;

namespace Users
{
	/// <summary>
	/// 
	/// </summary>
	public class UserWeb
	{
		const string NicknameCookieName = ".nickname";

		static HttpSessionState Session
		{
			get { return HttpContext.Current.Session; }
		}

		static HttpRequest Request
		{
			get { return HttpContext.Current.Request; }
		}

		static HttpResponse Response
		{
			get { return HttpContext.Current.Response; }
		}

		/// <summary>
		/// 获取当前在线用户的Id。
		/// 如果id等于-1，则表示当前用户是匿名（未登陆）用户。
		/// </summary>
		/// <returns></returns>
		public static int GetOnlineUserId()
		{
			string idStr = SsoAuthentication.GetIdentity();
			if (idStr == null) return -1;
			return Int32.Parse(idStr);
		}

		/// <summary>
		/// 是否为匿名（未登陆）用户。
		/// </summary>
		/// <returns></returns>
		public static bool IsAnonymous()
		{
			int userId = GetOnlineUserId();
			if (userId < 1) return true;
			return false;
		}

		/// <summary>
		/// 获取当前在线用户的User对象。
		/// 如果User对象为null，则表示当前用户是匿名（未登陆）用户。
		/// </summary>
		/// <returns></returns>
		public static User GetOnlineUser()
		{
			int userId = GetOnlineUserId();
			if (userId < 1) return null;
			return UsersSf.UserService.GetUser(userId);
		}

		/// <summary>
		/// 将浏览器重定向到登录URL。
		/// </summary>
		public static void RedirectToLoginPage()
		{
			string loginUrl = FormsAuthentication.LoginUrl;
			string returnUrl = HttpContext.Current.Request.Url.AbsoluteUri;
			returnUrl = HttpUtility.UrlEncode(returnUrl);
			// 登录完成后，需要返回当前Url，需要将当前Url的地址传递给登录页面
			if (loginUrl.Contains('?'))
			{
				loginUrl = loginUrl + "&ReturnUrl=" + returnUrl;
			}
			else
			{
				loginUrl = loginUrl + "?ReturnUrl=" + returnUrl;
			}

			Response.Redirect(loginUrl);
		}

		/// <summary>
		/// 将用户重定向回最初请求的URL或默认URL。
		/// </summary>
		public static void RedirectFromLoginPage()
		{
			string returnUrl = Request.QueryString["ReturnUrl"];
			if (String.IsNullOrEmpty(returnUrl))
			{
				returnUrl = FormsAuthentication.DefaultUrl;
			}
			Response.Redirect(returnUrl);
		}

		/// <summary>
		/// 登陆。
		/// </summary>
		/// <param name="username">用户名。</param>
		/// <param name="password">密码。</param>
		public static User Login(string username, string password)
		{
			if (!UsersSf.UserService.ValidateUser(username, password)) return null;
			User user = UsersSf.UserService.GetUser(username);
			Login(user);
			return user;
		}

		/// <summary>
		/// 通过邮箱登录
		/// </summary>
		/// <param name="email">邮箱</param>
		/// <param name="password">密码</param>
		/// <returns></returns>
		public static User LoginByEmail(string email, string password)
		{
			if (!UsersSf.UserService.ValidateUserByEmail(email, password))
			{
				return null;
			}
			User user = UsersSf.UserService.GetUserByEmail(email);
			Login(user);
			return user;
		}

		/// <summary>
		/// 登陆。用户已认证的情况下使用。
		/// </summary>
		/// <param name="user"></param>
		public static void Login(User user)
		{
			SsoAuthentication.SetAuthCookie(user.Id.ToString(), new TimeSpan(1, 0, 0, 0));
			SetNicknameCookie(user, new TimeSpan(1, 0, 0, 0));
		}

		/// <summary>
		/// 登出。
		/// </summary>
		public static void Logout()
		{
			SsoAuthentication.ClearAuthCookie();
			ClearNicknameCookie();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="user"></param>
		/// <param name="duration"></param>
		static void SetNicknameCookie(User user, TimeSpan duration)
		{
			string cookieValue = HttpUtility.UrlEncode(user.Nickname);
			HttpCookie nicknameCookie = new HttpCookie(NicknameCookieName);
			nicknameCookie.Value = cookieValue;
			nicknameCookie.Path = "/";
			nicknameCookie.Domain = FormsAuthentication.CookieDomain;
			nicknameCookie.Expires = DateTime.Now.Add(duration);
			Response.Cookies.Add(nicknameCookie);
		}

		/// <summary>
		/// 
		/// </summary>
		public static void ClearNicknameCookie()
		{
			HttpCookie ticketCookie = new HttpCookie(NicknameCookieName);
			ticketCookie.Value = null;
			ticketCookie.Path = "/";
			ticketCookie.Domain = FormsAuthentication.CookieDomain;
			ticketCookie.Expires = DateTime.Parse("1900-01-01");
			Response.Cookies.Add(ticketCookie);
		}
	}
}
